﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace ExcelXmlConverter.Utils
{
    public class XmlUtil
    {
        public static string SerializeDataTableXml(DataTable pDt)
        {
            try
            {
                if (pDt == null || pDt.Rows.Count == 0) return null;
                StringBuilder sb = new StringBuilder();
                XmlWriter writer = XmlWriter.Create(sb);
                XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
                serializer.Serialize(writer, pDt);
                writer.Close();
                return sb.ToString();
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public static DataTable DeserializeDataTable(string pXml)
        {
            try
            {
                StringReader strReader = new StringReader(pXml);
                XmlReader xmlReader = XmlReader.Create(strReader);
                XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
                DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
                return dt;
            }
            catch (Exception ex)
            {
                return new DataTable();
            }
        }
    }
}
